package c2.cross.business.admin;

import c2.advanced.share.RpcSuit;
import c2.cross.business.CrossBody;
import cate.game.admin.cross.CrossAdminCMDs;
import cate.game.admin.cross.CrossAdminReq;
import cp.solution.rpc.RpcMsgHead;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Slf4j
@NoteClass("跨服GM操作")
public class CrossAdminFacade {
    @NoteField("CrossBody")
    protected CrossBody context;
    @NoteField("GM功能Map")
    private final Map<String, Function<CrossAdminReq, String>> adminFunctionMap = new HashMap<>();

    public CrossAdminFacade(CrossBody context) {
        this.context = context;
    }

    /**
     * RPC
     */
    private RpcSuit rpc() {
        return context.rpc;
    }

    /**
     * RPC注册
     */
    public void rpcRegister() {
        rpc().recv().onRequestResponseTemplate(CrossAdminCMDs.CROSS_MSG, CrossAdminReq.class, this::onAdminReq);
    }

    /**
     * GM功能注册
     *
     * @param cmd      请求码
     * @param function 回调接口
     */
    public void functionRegister(String cmd, Function<CrossAdminReq, String> function) {
        if (adminFunctionMap.containsKey(cmd)) {
            log.error("[CrossAdminFacade] 重复注册GM请求！cmd={}", cmd);
            return;
        }
        log.info("[CrossAdminFacade] 注册了GM请求 cmd={}", cmd);
        adminFunctionMap.put(cmd, function);
    }

    /**
     * GM操作请求
     */
    private String onAdminReq(RpcMsgHead head, CrossAdminReq req) {
        if (req == null || req.cmd == null) {
            return "非法请求";
        }
        if (!adminFunctionMap.containsKey(req.cmd)) {
            return "未知操作";
        }
        try {
            return adminFunctionMap.get(req.cmd).apply(req);
        } catch (Exception e) {
            log.error("", e);
            return "操作异常";
        }
    }
}
